/*
 * @(#)NoSerialization.java, 2024/2/21 17:35
 *
 * Copyright (c) 2018-2024, 四川蜀天梦图数据科技有限公司.
 * All rights reserved.
 */
package controllers;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * NoSerialization
 *
 * @author fantazy
 * @version 1.0, 2024年02月21日
 */
public class NoCounter
{
    private static AtomicInteger noCounter;

    private static final String FILENAME = ".no.ser";

    static {
        if(Files.notExists(Paths.get(FILENAME))){
            noCounter = new AtomicInteger(0);
            try
            {
                serializeAtomicInteger( noCounter, FILENAME);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    private static void serializeAtomicInteger(AtomicInteger atomicInteger, String filename) throws IOException
    {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename)))
        {
            oos.writeObject(atomicInteger);
        }
    }

    private static AtomicInteger deserializeAtomicInteger(String filename) throws IOException, ClassNotFoundException
    {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename)))
        {
            return (AtomicInteger) ois.readObject();
        }
    }

    public static synchronized int nextNo()
    {
        int nextNo = -1;
        try
        {
            nextNo = (noCounter = deserializeAtomicInteger(FILENAME)).getAndIncrement();
            serializeAtomicInteger(noCounter, FILENAME);
            return nextNo;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        finally
        {
            return nextNo;
        }
    }
}
